<?php
include_once ("sys_info.php");               //获取板块信息
include_once ("../../config_controller.php");//后台的config，和前台类似。后期要整合成一个

$system_part = addslashes($_REQUEST ['sys_part']);//获取当前所在板块
$theme_folder = host_theme($_SERVER['HTTP_HOST']);//取得进入所输入的域名，确定theme_folder
include_once '../../front/' . $theme_folder . '/connection.php';
include_once '../common/script/check_session.php';
?>



<!-- 读取前台的config,，用来获取板块显示隐藏  -->
<?php include_once("function.php"); ?>
<?php include '../../front/' . $theme_folder . '/config.php'; ?>



<?php
//接收需要修改的数据的id
$new_detail_nid = addslashes($_REQUEST['nid']);
$old_detail=select_one_line_all_items($table_prefix."detail","nid = '".$_REQUEST['nid']."'");


//传递过来的页面信息。返回的时候，会根据这些信息返回原来的页面
$brand_id    = addslashes($_REQUEST['brand_id']);
$nowpageid    = addslashes($_REQUEST['nowpageid']);
$sortby       = addslashes($_REQUEST['sortby']);
$term_nid     = addslashes($_REQUEST['term_nid']);
$system_part  = addslashes($_REQUEST ['sys_part']);


$cat_list_json = json_decode($_REQUEST['cat_list_json'],true);  //关联文章信息处理

$new_cat_list = '';

if($_REQUEST['cat_list_json'] != ''){
	$cat_list_arr = array();
	foreach($cat_list_json as $cat_val){

		if(!empty($cat_val['children'])){
			$cat_list_arr [] = get_deep_id($cat_val['children']);
		}
		else{
			$cat_list_arr [] = $cat_val['id'];
		}

	}

	$new_cat_list = toOneArray($cat_list_arr);

}






//从组件获取的品牌的数据
$brand_list_json = json_decode($_REQUEST['brand_list_json'],true);

//print_r2($brand_list_json);


$new_brand_list = '';





//处理二级
if($_REQUEST['brand_list_json'] != '[]'){
	$brand_list_arr = array();
	foreach($brand_list_json as $brand_val){

	    //父子联动启动的时候写法，只记录子类
//		if(!empty($brand_val['children'])){
//			$brand_list_arr [] = get_deep_id($brand_val['children']);
//		}
//		else{
//			$brand_list_arr [] = $brand_val['id'];
//		}

        //父子联动取消的时候写法，记录父类和子类
        $brand_list_arr [] = get_deep_id($brand_val['children']);
        $brand_list_arr [] = $brand_val['id'];

    }

	//print_r2($brand_list_arr);
	static $res_arr = array();
	$new_brand_list = toOneArray($brand_list_arr,true);

}





$shop_list_json = json_decode($_REQUEST['shop_list_json'],true);  //关联文章信息处理


$new_shop_list = '';

if($_REQUEST['shop_list_json'] != '[]'){
	$shop_list_arr = array();
	foreach($shop_list_json as $shop_val){

		if(!empty($shop_val['children'])){
			$shop_list_arr [] = get_deep_id($shop_val['children']);
		}
		else{
			$shop_list_arr [] = $shop_val['id'];
		}

	}
	static $res_arr = array();
	$new_shop_list = toOneArray($shop_list_arr,true);

}



function toOneArray($array,$clear=false)
{
    static $res_arr = array();
	if ($clear)
    {
        $res_arr = array();
    }
    foreach ($array as $v) {
        if (is_array($v)) {
            toOneArray($v);
        } else {
            $res_arr[] = $v;
        }
    }
    return $res_arr;
}

function get_deep_id($list){
	$id_arr = array();
	foreach($list as $val){
		if(!empty($val['children'])){
			return  get_deep_id($val['children']);
		}

		$id_arr[] = $val['id'];

	}

	return $id_arr;
}





//所有插入新项的代码写在这里。
//====================================================
//设置表格和默认排序
$table_Suffix = $sys_list_table;
$table        = $table_Prefix.$table_Suffix;

$detail_attr_list = json_decode($_REQUEST['detail_attr'],true);  //关联文章信息处理

$goods_attr_list = json_decode($_REQUEST['goods_attr'],true);  //关联文章信息处理




//这里是设计上传文件的部分：包含图片和附件。视频也应该用这种形式上传
//统一设置一下保存图片的路径
$_uf['path']        = ROOT_PATH_ . "/uploadfiles/".$theme_folder."/";

//创建删除文件存放文件夹
if(!file_exists($_uf['path'] ."/delete/")){
    mkdir($_uf['path'] ."/delete/",0777,true);
    chmod($_uf['path'] ."/delete/",0777);
}




//上传icon
if (is_uploaded_file($_FILES['icon']['tmp_name']))
{
    $_uf['upfile']       = $_FILES['icon'];
    $_info               = upload_file($_uf);
    $_REQUEST['ai_icon'] = $_info['name'];
    if(($_REQUEST['ai_icon'])&&($old_detail['icon']!="alpha.gif"))
    {
        rename($_uf['path'].$old_detail['icon'], $_uf['path'] ."delete/".$old_detail['icon']);
    }
}

//上传Banner
if (is_uploaded_file($_FILES['banner']['tmp_name']))
{
    $_uf['upfile']       = $_FILES['banner'];
    $_info               = upload_file($_uf);
    $_REQUEST['ai_banner'] = $_info['name'];
    if(($_REQUEST['ai_banner'])&&($old_detail['banner']!="alpha.gif")){
        rename($_uf['path'].$old_detail['banner'], $_uf['path'] ."delete/".$old_detail['banner']);
    }
}

//上传image1
if (is_uploaded_file($_FILES['image1']['tmp_name']))
{
    $_uf['upfile']         = $_FILES['image1'];
    $_info                 = upload_file($_uf);
    $_REQUEST['ai_image1'] = $_info['name'];
    if(($_REQUEST['ai_image1'])&&($old_detail['image1']!="alpha.gif")){
        rename($_uf['path'].$old_detail['image1'], $_uf['path'] ."delete/".$old_detail['image1']);
    }
}

//上传image2
if (is_uploaded_file($_FILES['image2']['tmp_name']))
{
    $_uf['upfile']         = $_FILES['image2'];
    $_info                 = upload_file($_uf);
    $_REQUEST['ai_image2'] = $_info['name'];
    if(($_REQUEST['ai_image2'])&&($old_detail['image2']!="alpha.gif")){
        rename($_uf['path'].$old_detail['image2'], $_uf['path'] ."delete/".$old_detail['image2']);
    }
}

//上传image3
if (is_uploaded_file($_FILES['image3']['tmp_name']))
{
    $_uf['upfile']         = $_FILES['image3'];
    $_info                 = upload_file($_uf);
    $_REQUEST['ai_image3'] = $_info['name'];
    if(($_REQUEST['ai_image3'])&&($old_detail['image3']!="alpha.gif")){
        rename($_uf['path'].$old_detail['image3'], $_uf['path'] ."delete/".$old_detail['image3']);
    }
}


//上传image4
if (is_uploaded_file($_FILES['image4']['tmp_name']))
{
    $_uf['upfile']         = $_FILES['image4'];
    $_info                 = upload_file($_uf);
    $_REQUEST['ai_image4'] = $_info['name'];
    if(($_REQUEST['ai_image4'])&&($old_detail['image4']!="alpha.gif")){
        rename($_uf['path'].$old_detail['image4'], $_uf['path'] ."delete/".$old_detail['image4']);
    }
}



//上传image5
if (is_uploaded_file($_FILES['image5']['tmp_name']))
{
    $_uf['upfile']         = $_FILES['image5'];
    $_info                 = upload_file($_uf);
    $_REQUEST['ai_image5'] = $_info['name'];
    if(($_REQUEST['ai_image5'])&&($old_detail['image5']!="alpha.gif")){
        rename($_uf['path'].$old_detail['image5'], $_uf['path'] ."delete/".$old_detail['image5']);
    }
}





//上传image6
if (is_uploaded_file($_FILES['image6']['tmp_name']))
{
	$_uf['upfile']         = $_FILES['image6'];
	$_info                 = upload_file($_uf);
	$_REQUEST['ai_image6'] = $_info['name'];
}


//上传image7
if (is_uploaded_file($_FILES['image7']['tmp_name']))
{
	$_uf['upfile']         = $_FILES['image7'];
	$_info                 = upload_file($_uf);
	$_REQUEST['ai_image7'] = $_info['name'];
}


//上传image8
if (is_uploaded_file($_FILES['image8']['tmp_name']))
{
	$_uf['upfile']         = $_FILES['image8'];
	$_info                 = upload_file($_uf);
	$_REQUEST['ai_image8'] = $_info['name'];
}


//上传image9
if (is_uploaded_file($_FILES['image9']['tmp_name']))
{
	$_uf['upfile'] = $_FILES['image9'];
	$_info                 = upload_file($_uf);
	$_REQUEST['ai_image9'] = $_info['name'];
}


//上传image10
if (is_uploaded_file($_FILES['image10']['tmp_name'])) {
	$_uf['upfile']          = $_FILES['image10'];
	$_info                  = upload_file($_uf);
	$_REQUEST['ai_image10'] = $_info['name'];
}



//上传备用图片
if (is_uploaded_file($_FILES['extend_img']['tmp_name'])) {
    $_uf['upfile']             = $_FILES['extend_img'];
    $_info                     = upload_file($_uf);
    $_REQUEST['ai_extend_img'] = $_info['name'];
    if(($_REQUEST['ai_extend_img'])&&($old_detail['extend_img']!="alpha.gif")){
        rename($_uf['path'].$old_detail['extend_img'], $_uf['path'] ."delete/".$old_detail['extend_img']);
    }
}


//上传附件
if (is_uploaded_file($_FILES['attachment']['tmp_name'])) {
    $_uf["allowExt"] = array('jpeg',
                             'jpg',
                             'png',
                             'gif',
                             'rar',
                             'zip',
                             '7zip',
                             'exe',
                             'msi',
                             'txt',
                             'doc',
                             'xlsx',
                             'pptx',
                             'pdf',
                             'webp');
    $_uf['upfile']             = $_FILES['attachment'];
    $_info                     = upload_file($_uf);
    $_REQUEST['ai_attachment'] = $_info['name'];
    if($_REQUEST['ai_attachment']){
        rename($_uf['path'].$old_detail['attachment'], $_uf['path'] ."delete/".$old_detail['attachment']);
    }
}




//处理一下要更新的数据
//检查表是否有这个字段,如果没有自动生成,
//unid是数据指纹。20200223126003+xxxxxxxxxxxx10位随机数组成，是绝对唯一的

if(!$old_detail['unid'])
{
    $_REQUEST['ai_unid']         = date("YmdHis").rand(1000000000,9999999999);
}



//用程序消除外链地址最后打斜杠'/','\'

//把字符串中的反斜杠转义成斜杠
$_REQUEST['ai_storage'] = str_replace("\\", "/", $_REQUEST['ai_storage']);

/*转义之后反斜杠会变成'//',函数中在末尾添加@，变成//@,用来和http://中的区分*/
if (substr($_REQUEST['ai_storage'], -2, 2) == "//") {
    $_REQUEST['ai_storage'] = $_REQUEST['ai_storage'] . "@";
    $_REQUEST['ai_storage'] = str_replace("//@", "", $_REQUEST['ai_storage']);
}

if (substr($_REQUEST['ai_storage'], -1, 1) == "/") {
    $_REQUEST['ai_storage'] = $_REQUEST['ai_storage'] . "@";
    $_REQUEST['ai_storage'] = str_replace("/@", "", $_REQUEST['ai_storage']);
}

?>





<?
//关于时间的一些数据,修正一下数据
//如果传过来的时间是空的或者错误的（错误判别为出现1970），就用现在时间替换。

if((!$_REQUEST['ai_publish'])or(strstr($_REQUEST['ai_publish'],"1970")))
{
    $_REQUEST['ai_publish']=date("Y-m-d H:s:i");
}


if((!$_REQUEST['ai_inputtime'])or(strstr($_REQUEST['ai_inputtime'],"1970")))
{
    echo $_REQUEST['ai_inputtime']=date("Y-m-d H:s:i");
}


if((!$_REQUEST['ai_modifytime'])or(strstr($_REQUEST['ai_modifytime'],"1970")))
{
    $_REQUEST['ai_modifytime']=date("Y-m-d H:s:i");
}








//设置需要搜索的表格的前缀后缀
$table_Suffix = $sys_list_table;
$table = $table_Prefix . $table_Suffix;
//设置需要搜索的表格的前缀后缀
$tempdata = select_image_row($table,$new_detail_nid);
$sqlstr=update_date($table,$_REQUEST,'nid',$_REQUEST['nid']);



sql_log($sqlstr);
$query = mysql_query($sqlstr) or die ("error:".mysql_error());

$tempdata_new = select_image_row($table,$new_detail_nid);
$img_path_pix = '../../uploadfiles/' . $theme_folder . '/';
delect_local_img($tempdata_new,$tempdata,$img_path_pix);





//关联文章
$sql = "DELETE FROM ".$table_Prefix."detail_relation where goods_id = ".$_REQUEST['nid'];
sql_log($sql);
mysql_query($sql);

if(count($detail_attr_list) > 0){



	foreach($detail_attr_list as $val){

		$sql = "INSERT INTO ".$table_Prefix."detail_relation ( `goods_id`, `detail_id`) VALUES ('".$_REQUEST['nid'] ."','".$val['value']."')";

		sql_log($sql);
mysql_query($sql);
	}
}


//关联商品
$sql = "DELETE FROM ".$table_Prefix."goods_term_relation where product_id = ".$_REQUEST['nid'];
sql_log($sql);
mysql_query($sql);

if(count($goods_attr_list) > 0){



    foreach($goods_attr_list as $val){

        $sql = "INSERT INTO ".$table_Prefix."goods_term_relation ( `product_id`, `goods_id`) VALUES ('".$_REQUEST['nid'] ."','".$val['value']."')";

        sql_log($sql);
        mysql_query($sql);
    }
}



mysql_close($con);

?>










<!--
下面这部分是关于分类等等的，需要处理。
===================================================================
1.realtion
2.上传图片或者文件的时候，要删除旧的文件。
-->








<?php
//纯数字型的数据，要判空默认处理
if(!$_REQUEST['ai_vip'])
{
    $_REQUEST['ai_vip']=0;
}
$new_detail_vip = $_REQUEST['ai_vip'];
?>









<?

/*插入新的detail与term关系表*/


/*思路是
1.分解传递过来的分类号码
2.查detail对term数据是否存在
3.存在就不用理，不存在就插入



那么怎么删除呢？

思路是
分解传递过来的分类号码

查出所有detail对term数据
detail能对得上新的term，就保留
detail对不上term，就删除

那么怎么删除呢
*/


//设置需要搜索的表格的前缀后缀
$table_Suffix = "relation";
$table = $table_Prefix . $table_Suffix;
//设置需要搜索的表格的前缀后缀


//1.checkbox传递过来的数组分解开

$term_detail_list = $new_cat_list;

if($term_detail_list ){

	$query = mysql_query("SELECT * FROM $table where detail_nid = '$new_detail_nid' AND belong is NULL ");

	$cat_list_id= array();

	while ($row = mysql_fetch_array($query)) {

		$cat_list[] = $row;

	}


	if($cat_list){ //如果有保存的分类 先处理
		foreach($cat_list as $value){
			if(!in_array($value['term_nid'],$term_detail_list)){  //不存在就删除
				$sql = " DELETE FROM $table WHERE nid=$value[nid] AND belong is NULL  ";
				sql_log($sql);
	$query = mysql_query($sql) ;

			}
			foreach($term_detail_list as $key1=>$value1){ //过滤相同的参数
				if($value1 == $value['term_nid']){
					unset($term_detail_list[$key1]);
				}
			}
		}

		foreach($term_detail_list as $value2){//过滤后的直接插入
			 $sql = "INSERT INTO $table (
					detail_nid,
					term_nid,
					vip_term
					)
					
					value (
					
					'$new_detail_nid',
					'$value2',
					'$new_detail_vip'
					)";

			sql_log($sql);
	$query = mysql_query($sql) or die ('572 添加数据失败'. mysql_error());
		}
	}
	else{
		foreach($term_detail_list as $value2){
			 $sql = "INSERT INTO $table (
					detail_nid,
					term_nid,
					vip_term
					)
					
					value (
					
					'$new_detail_nid',
					'$value2',
					'$new_detail_vip'
					)";

			sql_log($sql);
	$query = mysql_query($sql) or die ('添加数据失败 591 ：'. mysql_error());
		}
	}
}

$brand_detail_list = $new_brand_list;;


	$query = mysql_query("SELECT * FROM $table where detail_nid = '$new_detail_nid' AND belong = 'brand' ");

	$brand_list_id= array();

	while ($row = mysql_fetch_array($query)) {

		$brand_list[] = $row;

	}
	if($brand_list){ //如果有保存的分类 先处理
		foreach($brand_list as $value){
			if(!in_array($value['term_nid'],$brand_detail_list)){  //不存在就删除
				$sql = " DELETE FROM $table WHERE nid=$value[nid] AND belong  = 'brand' ";
				sql_log($sql);
	$query = mysql_query($sql) ;

			}
			if($brand_detail_list){
				foreach($brand_detail_list as $key1=>$value1){ //过滤相同的参数
					if($value1 == $value['term_nid']){
						unset($brand_detail_list[$key1]);
					}
				}
			}
		}

		if($brand_detail_list){
			foreach($brand_detail_list as $value2){//过滤后的直接插入
				 $sql = "INSERT INTO $table (
						detail_nid,
						term_nid,
						vip_term,
						belong
						)
						
						value (
						
						'$new_detail_nid', 
						'$value2',
						'$new_detail_vip',
						'brand'
						)";

				sql_log($sql);
				$query = mysql_query($sql) or die ('649 添加数据失败'. mysql_error());
			}
		}
	}
	else{
		if($brand_detail_list){
			foreach($brand_detail_list as $value2){
				 $sql = "INSERT INTO $table (
						detail_nid,
						term_nid,
						vip_term,
						belong
						)
						
						value (
						
						'$new_detail_nid',
						'$value2',
						'$new_detail_vip',
						'brand'
						)";

				sql_log($sql);
				$query = mysql_query($sql) or die ('672 添加数据失败'. mysql_error());
			}
		}
	}



$shop_detail_list = $new_shop_list;;


	$query = mysql_query("SELECT * FROM $table where detail_nid = '$new_detail_nid' AND belong = 'shop' ");

	$shop_list_id= array();

	while ($row = mysql_fetch_array($query)) {

		$shop_list[] = $row;

	}

	if($shop_list){ //如果有保存的分类 先处理
		foreach($shop_list as $value){
			if(!in_array($value['term_nid'],$shop_detail_list)){  //不存在就删除
				$sql = " DELETE FROM $table WHERE nid=$value[nid] AND belong  = 'shop' ";
				sql_log($sql);
				$query = mysql_query($sql) ;

			}
			if($shop_detail_list){
				foreach($shop_detail_list as $key1=>$value1){ //过滤相同的参数
					if($value1 == $value['term_nid']){
						unset($shop_detail_list[$key1]);
					}
				}
			}
		}
		if($shop_detail_list){
			foreach($shop_detail_list as $value2){//过滤后的直接插入
				 $sql = "INSERT INTO $table (
						detail_nid,
						term_nid,
						vip_term,
						belong
						)
						
						value (
						
						'$new_detail_nid', 
						'$value2',
						'$new_detail_vip',
						'shop'
						)";

				sql_log($sql);
				$query = mysql_query($sql) or die ('添加数据失败'. mysql_error());
			}
		}
	}
	else{
		if($shop_detail_list){
			foreach($shop_detail_list as $value2){
				 $sql = "INSERT INTO $table (
						detail_nid,
						term_nid,
						vip_term,
						belong
						)
						
						value (
						
						'$new_detail_nid',
						'$value2',
						'$new_detail_vip',
						'shop'
						)";

				sql_log($sql);
				$query = mysql_query($sql) or die ('添加数据失败'. mysql_error());
			}
		}
	}



$img_url_count = count($_FILES['img_url']['tmp_name']);



if($img_url_count > 0){


	foreach($_FILES['img_url']['tmp_name'] as $imgkey=>$imgval){



	if (is_uploaded_file($_FILES['img_url']['tmp_name'][$imgkey])) {
		$upfile = $_FILES["img_url"];
    //获取数组里面的值



		$img_name = explode(".",$upfile["name"][$imgkey]); //上传的文件名改为时间命名
		$name = date("YmdHis",time()).rand(10,99).'.'.$img_name[1];

		$type = $upfile["type"][$imgkey]; //上传文件的类型


		$size = $upfile["size"][$imgkey]; //上传文件的大小
		$tmp_name = $upfile["tmp_name"][$imgkey]; //上传文件的临时存放路径
		/*
		这是一种非常简单文件上传方式。基于安全方面的考虑，您应当增加有关什么用户有权上传文件的限制。
		上传限制
		在这个脚本中，我们增加了对文件上传的限制。用户只能上传 .gif 或 .jpeg 文件
		*/
		switch ($type) {
			case 'image/pjpeg':
				$okType = true;
				break;
			case 'image/jpeg':
				$okType = true;
				break;
			case 'image/gif':
				$okType = true;
				break;
			case 'image/png':
				$okType = true;
				break;
            case 'image/webp':
                $okType = true;
                break;
		}


		if ($okType) {
			/**
			 * 0:文件上传成功<br/>
			 * 1：超过了文件大小，在php.ini文件中设置<br/>
			 * 2：超过了文件的大小MAX_FILE_SIZE选项指定的值<br/>
			 * 3：文件只有部分被上传<br/>
			 * 4：没有文件被上传<br/>
			 * 5：上传文件大小为0
			 */
			$error = $upfile["error"][$imgkey]; //上传后系统返回的值
			echo "================<br/>";
			echo "上传文件名称是：" . $name . "<br/>";
			echo "上传文件类型是：" . $type . "<br/>";
			echo "上传文件大小是：" . $size . "<br/>";
			echo "上传后系统返回的值是：" . $error . "<br/>";
			echo "上传文件的临时存放路径是：" . $tmp_name . "<br/>";

			echo "开始移动上传文件<br/>";
			//把上传的临时文件移动到up目录下面
			move_uploaded_file($tmp_name, '../../uploadfiles/' . $theme_folder . '/' . $name);
			$icon = $name;
			echo "================<br/>";
			echo "上传信息：<br/>";
			if ($error == 0) {
				echo "文件上传成功啦！";
				echo "<br>图片预览:<br>";
				echo "<img src=" . $icon . ">";
				//echo " alt="图片预览:r文件名:".$destination."r上传时间:">";
			} elseif ($error == 1) {
				echo "超过了文件大小，在php.ini文件中设置";
			} elseif ($error == 2) {
				echo "超过了文件的大小MAX_FILE_SIZE选项指定的值";
			} elseif ($error == 3) {
				echo "文件只有部分被上传";
			} elseif ($error == 4) {
				echo "没有文件被上传";
			} else {
				echo "上传文件大小为0";
			}
		} else {
			echo "请上传jpg,gif,png等格式的图片！";
		}



		$img_title = $_REQUEST['img_title'][$imgkey];
		$img_desc = $_REQUEST['img_desc'][$imgkey];
		$img_price = $_REQUEST['img_price'][$imgkey];
		$sql = "INSERT INTO ".$table_Prefix."product_attr ( img_title,img_desc,img_url,img_price , detail_nid) VALUES ('".$img_title ."','".$img_desc."','".$name ."','".$img_price."','".$new_detail_nid."')";

		sql_log($sql);
		mysql_query($sql);;
	}
}

}


if (isset($_POST['old_img_title']))
{
   foreach ($_POST['old_img_title'] AS $img_id => $img_title)
   {
       $sql = "UPDATE " . $table_Prefix. "product_attr SET img_title = '$img_title' , img_desc = '".$_POST['old_img_desc'][$img_id]."', img_price = '".$_POST['old_img_price'][$img_id]."' WHERE nid = '$img_id' LIMIT 1";
       sql_log($sql);
	   mysql_query($sql) or die ( error_log());

   }
}

?>








<script type="text/javascript">

    alert("输入信息已保存，点击确认返回继续操作.");
    document.location.href = "detail-list.php?brand_id=<? echo $brand_id ?>&nowpageid=<? echo $nowpageid ?>&sortby=<? echo $sortby?>&nid=<? echo $term_nid ?>&sys_part=<? echo $system_part ?>"

</script>



